package com.zsc.koail.camerarecorder.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.werb.permissionschecker.PermissionChecker;
import com.zsc.koail.camerarecorder.widget.DisplayVideoView;
import com.zsc.koail.camerarecorder.R;
import com.zsc.koail.camerarecorder.RecorderService;
import com.zsc.koail.camerarecorder.adapter.VideoAdapter;
import com.zsc.koail.camerarecorder.bean.VideoBean;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity {
    private PermissionChecker mPermissionChecker;
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.SYSTEM_ALERT_WINDOW,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.READ_PHONE_STATE,
            Manifest.permission.PROCESS_OUTGOING_CALLS,
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE
    };

    private RecorderService mRecorderService;
    private ServiceConnection mConnection;
    //    private ListView mListView;
    private DisplayVideoView mVideoView;
    private VideoAdapter mAdapter;
    private String mNewestVideoPath;
    private static final String TAG = "MainActivity";
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    break;
                case 1:
                    break;
            }
        }
    };
    private File videoDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mPermissionChecker = new PermissionChecker(this);
        //        mListView = this.findViewById(R.id.video_List);
        mVideoView = this.findViewById(R.id.video);
        //        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        //            @Override
        //            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //                playVideo(mAdapter.getVideo(position).getPath());
        //
        //            }
        //        });
        mAdapter = new VideoAdapter(new ArrayList<VideoBean>());
        //        mListView.setAdapter(mAdapter);
        this.findViewById(R.id.open).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startBackService();
            }
        });

        this.findViewById(R.id.start).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "开始录制");
                if (mRecorderService != null) {
                    mRecorderService.startRecord();
                }
            }
        });

        this.findViewById(R.id.end).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "结束录制并保存");
                if (mRecorderService != null) {
                    mNewestVideoPath = mRecorderService.stopRecordSave();
                    //                    loadVideo();
                }
            }
        });

        this.findViewById(R.id.play).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(mNewestVideoPath)) {
                    playVideo(mNewestVideoPath);
                }
            }
        });
        //        loadVideo();
    }

    @Override
    protected void onStart() {
        super.onStart();
        if (mPermissionChecker.isLackPermissions(PERMISSIONS)) {
            mPermissionChecker.requestPermissions();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PermissionChecker.PERMISSION_REQUEST_CODE:
                break;
        }
    }


    private void playVideo(String path) {
        mVideoView.stopPlayback();
        mVideoView.setVideoPath(path);
        mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mp.start();
            }
        });
    }

    private void loadVideo() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final List<VideoBean> videoBeanList = new ArrayList<VideoBean>();
                if (videoDir.exists()) {
                    File[] videoFiles = videoDir.listFiles();
                    for (File videoFile : videoFiles) {
                        Log.d(TAG, videoFile.getAbsolutePath());
                        if (videoFile.getName().endsWith(".mp4")) {
                            VideoBean e = new VideoBean();
                            e.setBitmap(getVideoThumbNail(videoFile.getAbsolutePath()));
                            e.setName(videoFile.getName());
                            e.setPath(videoFile.getAbsolutePath());
                            videoBeanList.add(e);
                        }
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAdapter.notifyVideo(videoBeanList);
                        }
                    });
                }
            }
        }).start();
    }

    private void startBackService() {
        Intent service = new Intent(this, RecorderService.class);
        mConnection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                mRecorderService = ((RecorderService.RecorderBinder) service).getService();
                Toast.makeText(MainActivity.this, "后台录像功能开启成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {

            }
        };
        bindService(service, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            if (mConnection != null) {
                unbindService(mConnection);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public Bitmap getVideoThumbNail(String filePath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }
}
